package com.df.barcodescaning.util;

import android.content.Context;
import android.content.SharedPreferences;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 缓存
 * @author Gzs
 */
public class FileLocalCache {

    /**
     * 检测文件是否存在,不存在则创建
     */
    public static boolean checkDir(String filePath){
        File f = new File("filePath");
        if (!f.exists()) {
            return f.mkdirs();
        }
        return true;
    }

    /**
     * 返回MD5加密后的值
     */
    public static String md5(String url){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(url.getBytes("UTF-8"));
            byte messageDigest[] = md5.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String t = Integer.toHexString(0xFF & messageDigest[i]);
                if (t.length() == 1) {
                    hexString.append("0"+t);
                } else {
                    hexString.append(t);
                }
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 为对象进行序列化
     * @param context
     * @param object
     * @param fileName
     */
    public static void setSerializableData(Context context, Object object, String fileName){
        String dir = FileUtils.getCacheDir(context);
        try {
            FileOutputStream byteOut = new FileOutputStream(new File(dir + md5(fileName)));
            ObjectOutputStream output = new ObjectOutputStream(byteOut);
            output.writeObject(object);
            output.flush();
            output.close();
//			byteOut.flush();
            byteOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取得序列化数据
     * @param context
     * @param fileName
     * @return
     */
    public static Object getSerializableData(Context context,String fileName) {
        String dir= FileUtils.getCacheDir(context);
        Object obj = null;
        try {
            File d = new File(dir);
            if (!d.exists()){
                d.mkdirs();
            }
            File f = new File(dir +md5(fileName));
            if (!f.exists()){
                f.createNewFile();
            }
            if (f.length() == 0){
                return null;
            }
            FileInputStream byteOut = new FileInputStream(f);
            ObjectInputStream out = new ObjectInputStream(byteOut);
            obj=out.readObject();
            out.close();
            try {
                if(byteOut!=null){
                    byteOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (OptionalDataException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * @Description: 删除序列化数据
     * @param context
     * @param fileName
     */
    public static void delSerializableData(Context context,String fileName){
        String dir= FileUtils.getCacheDir(context);
        File d = new File(dir);
        if (!d.exists()){
            d.mkdirs();
        }
        File f = new File(dir +md5(fileName));
        if (f.exists()){
            f.delete();
        }
    }

    /**
     * 保存历史记录
     */
    public static void saveSearchHistory(Context context, String searchText, String saveName){
        SharedPreferences sp = context.getSharedPreferences("search_history", Context.MODE_PRIVATE);
        String oldText = sp.getString(saveName, "no search history");	//key, defValue

        StringBuilder sb = new StringBuilder(oldText);
        sb.append(searchText + ",");


        //判断搜索内容是否已经存在于历史记录中，若已存在就不需要添加
        if(!oldText.contains(searchText+",")){
            SharedPreferences.Editor spEditor = sp.edit();
            spEditor.putString(saveName, sb.toString());
            spEditor.commit();
        }

    }

    /**
     * 获取搜索记录文件内容:
     */
    public static String[] getSearchHistory(Context context, String saveName){
        SharedPreferences sp = context.getSharedPreferences("search_history", Context.MODE_PRIVATE);
        String history = sp.getString(saveName, "no search history");

        // 用逗号分割内容返回数组
        String[] history_arr = history.split(",");

        // 保留前50条数据
        if (history_arr.length > 8) {
            String[] newArrays = new String[8];
            // 实现数组之间的复制
            System.arraycopy(history_arr, 0, newArrays, 0, 8);
            return newArrays;
        }

        return history_arr;
    }
}
